//
//  User.m
//  TwitterPlane
//
//  Created by kazuyuki takahashi on 10/01/26.
//  Copyright 2010 by invisibledesigner.com. All rights reserved.
//

#import "User.h"
#import "NSString+XML.h"

static NSString *myScreenName = nil;

@implementation User

@synthesize userID = userID_;
@synthesize name = name_;
@synthesize screenName = screenName_;
@synthesize isProtected = isProtected_;
@synthesize profileImageURL = profileImageURL_;
@dynamic profileURL;

+ (id)userForDictionary:(NSDictionary *)dic
{
    NSParameterAssert(dic != nil);
    
    NSAssert([NSThread isMainThread], @"needs lock");
    static NSCache *cache = nil;
    if (cache == nil) {
        cache = [[NSCache alloc] init];
    }
    
    NSString *userid = [dic objectForKey:@"id"];
    if (userid == nil) {
        return nil;
    }
    
    //キャッシュに同じIDのオブジェクトがあれば返し、なければ新しいオブジェクトを作成
    id obj = [cache objectForKey:userid];
    if (obj != nil) {
        return obj;
    }
    
    id user = [[[self alloc] initWithDictionary:dic] autorelease];
    if (user == nil) {
        return nil;
    }
    
    [cache setObject:user forKey:userid];
    return user;
}

- (id)initWithDictionary:(NSDictionary *)dic
{
    NSParameterAssert(dic != nil);
    self = [super init];
    if (self) {
        userID_ = [[dic objectForKey:@"id"] retain];
        name_ = [[[dic objectForKey:@"name"] stringByUnescapingXMLSpecialChars] retain];
        screenName_ = [[[dic objectForKey:@"screen_name"] stringByUnescapingXMLSpecialChars] retain];
        isProtected_ = [[dic objectForKey:@"protected"] boolValue];
        NSString *urlstr = [dic objectForKey:@"profile_image_url"];
        if (urlstr != nil) {
            profileImageURL_ = [[NSURL alloc] initWithString:urlstr];
        }
        
        if (!(userID_ && name_ && screenName_ && profileImageURL_)) {
            NSAssert(NO, @"invalid parameters");
            [self release];
            self = nil;
        }
    }
    return self;
}

- (id)init 
{
    NSAssert(NO, @"invalid initializer");
    [self release];
    return self = nil;
}

- (NSURL*)profileURL
{
    return [NSURL URLWithString:[@"http://twitter.com/" stringByAppendingString:[self screenName]]];
}

- (void)dealloc
{
    [userID_ release];
    [name_ release];
    [screenName_ release];
    [profileImageURL_ release];
    [super dealloc];
}

+ (NSString*)myScreenName
{
    return myScreenName;
}

+ (void)setMyScreenName:(NSString*)name
{
    [myScreenName autorelease];
    myScreenName = [name copy];
}

@end
